import React, { useState } from 'react';
import { Button, message } from 'antd';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import { FormattedMessage } from '@@/plugin-locale';
import { createUser } from '@/services/api/user';

const handleAdd = async (fields: API.UserCreateDto) => {
  const hide = message.loading('正在添加');
  try {
    const { status_code, message: msg } = await createUser({ ...fields });
    if (status_code === 200) {
      hide();
      message.success(msg);
      return true;
    }
    message.error(msg);
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

type AddUserViewProps = {
  onSubmit: () => void;
};

const AddUser: React.FC<AddUserViewProps> = (props) => {
  const { onSubmit } = props;
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  return (
    <>
      <Button
        type="primary"
        key="primary"
        onClick={() => {
          handleModalVisible(true);
        }}
      >
        <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
      </Button>
      <ModalForm
        isKeyPressSubmit={false}
        title={'新建用户'}
        width="400px"
        open={modalVisible}
        onOpenChange={() => {
          handleModalVisible(false);
        }}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.UserCreateDto);
          if (success) {
            onSubmit();
            handleModalVisible(false);
          }
        }}
      >
        <ProFormText
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: '用户名为必填项',
            },
          ]}
        />
        <ProFormText.Password
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '密码为必填项',
            },
          ]}
        />
        <ProFormSelect
          name="role"
          label="权限"
          initialValue="ROLE_GUEST"
          valueEnum={{
            ROLE_GUEST: '普通用户',
            ROLE_ADMIN: '超级用户',
          }}
          rules={[
            {
              required: true,
              message: '权限为必选项',
            },
          ]}
        />
      </ModalForm>
    </>
  );
};
export default AddUser;
